<?php
// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 检查数据库表状态
global $wpdb;
$stats_table = $wpdb->prefix . 'spider_stats';
$visits_table = $wpdb->prefix . 'spider_visits';

$visits_exists = $wpdb->get_var("SHOW TABLES LIKE '$visits_table'") == $visits_table;
$stats_exists = $wpdb->get_var("SHOW TABLES LIKE '$stats_table'") == $stats_table;
$tables_exist = $visits_exists && $stats_exists;

// 获取参数
$spider_name = isset($_GET['spider']) ? sanitize_text_field($_GET['spider']) : '';
$date = isset($_GET['date']) ? sanitize_text_field($_GET['date']) : current_time('Y-m-d');

// 统一北京时间窗口（当天 00:00:00 ~ 23:59:59）
try {
    $tz = new \DateTimeZone('Asia/Shanghai');
    $dayStart = (new \DateTimeImmutable($date, $tz))->setTime(0,0,0)->format('Y-m-d H:i:s');
    $dayEnd   = (new \DateTimeImmutable($date, $tz))->setTime(23,59,59)->format('Y-m-d H:i:s');
} catch (\Exception $e) {
    $dayStart = $date . ' 00:00:00';
    $dayEnd   = $date . ' 23:59:59';
}

// 获取蜘蛛详情数据
$spider_details = array();
$spider_urls = array();
$total_visits = 0;
$total_pages = 0;
$avg_response_time = 0;

if ($tables_exist && $spider_name) {
    // 用访问表在北京时间窗口聚合，保证与首页一致
    $agg = $wpdb->get_row($wpdb->prepare(
        "SELECT COUNT(*) as visit_count,
                COUNT(DISTINCT url) as unique_pages,
                AVG(response_time) as avg_response_time,
                MAX(visit_time) as last_visit
         FROM $visits_table
         WHERE spider_name = %s AND visit_time BETWEEN %s AND %s",
        $spider_name, $dayStart, $dayEnd
    ), ARRAY_A);

    if ($agg) {
        $total_visits = intval($agg['visit_count']);
        $total_pages = intval($agg['unique_pages']);
        $avg_response_time = (float)$agg['avg_response_time'];
        $spider_details = array(
            'visit_count' => $total_visits,
            'unique_pages' => $total_pages,
            'avg_response_time' => $avg_response_time,
            'last_visit' => $agg['last_visit']
        );
    }

    // 获取访问的URL列表（北京时间日内）
    $spider_urls = $wpdb->get_results($wpdb->prepare(
        "SELECT * FROM $visits_table WHERE spider_name = %s AND visit_time BETWEEN %s AND %s ORDER BY visit_time DESC LIMIT 100",
        $spider_name, $dayStart, $dayEnd
    ), ARRAY_A);
}

// 获取所有蜘蛛列表
$all_spiders = array();
if ($tables_exist) {
    // 当天活跃蜘蛛（北京时间窗口）
    $all_spiders = $wpdb->get_results($wpdb->prepare(
        "SELECT spider_name, COUNT(*) as total_visits
         FROM $visits_table
         WHERE visit_time BETWEEN %s AND %s
         GROUP BY spider_name
         ORDER BY total_visits DESC",
        $dayStart, $dayEnd
    ), ARRAY_A);
}
?>

<div class="wp-spider-monitor-container">
    <!-- 头部区域 -->
    <div class="spider-monitor-header">
        <div class="header-content">
            <div>
                <h1 class="header-title">📊 访问详情</h1>
                <p class="header-subtitle">查看详细的蜘蛛访问记录和页面访问情况</p>
            </div>
            <div class="header-actions">
                <a href="<?php echo admin_url('admin.php?page=wp-spider-monitor'); ?>" class="btn btn-secondary">
                    <span>←</span> 返回首页
                </a>
                <button id="refresh-details" class="btn btn-primary">
                    <span>🔄</span> 刷新数据
                </button>
            </div>
        </div>
    </div>

    <!-- 筛选器 -->
    <div class="filter-section">
        <div class="filter-card">
            <div class="filter-header">
                <h3>筛选条件</h3>
            </div>
            <div class="filter-content">
                <div class="filter-group">
                    <label for="spider-select">选择蜘蛛：</label>
                    <select id="spider-select" class="filter-select">
                        <option value="">-- 选择蜘蛛 --</option>
                        <?php foreach ($all_spiders as $spider): ?>
                            <option value="<?php echo esc_attr($spider['spider_name']); ?>" 
                                    <?php selected($spider_name, $spider['spider_name']); ?>>
                                <?php echo esc_html($spider['spider_name']); ?> 
                                (<?php echo number_format($spider['total_visits']); ?> 次访问)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="date-select">选择日期：</label>
                    <input type="date" id="date-select" class="filter-input" value="<?php echo esc_attr($date); ?>">
                </div>
                <div class="filter-group">
                    <button id="apply-filter" class="btn btn-primary">应用筛选</button>
                </div>
            </div>
        </div>
    </div>

    <?php if ($spider_name && $spider_details): ?>
        <!-- 蜘蛛概览 -->
        <div class="spider-overview">
            <div class="overview-header">
                <div class="spider-info">
                    <div class="spider-avatar <?php echo strtolower($spider_name); ?>">
                        <?php echo strtoupper(substr($spider_name, 0, 2)); ?>
                    </div>
                    <div class="spider-details">
                        <h2><?php echo esc_html($spider_name); ?></h2>
                        <p>访问日期: <?php echo date('Y年m月d日', strtotime($date)); ?></p>
                    </div>
                </div>
                <div class="spider-stats-overview">
                    <div class="stat-item">
                        <div class="stat-value"><?php echo number_format($total_visits); ?></div>
                        <div class="stat-label">访问次数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?php echo number_format($total_pages); ?></div>
                        <div class="stat-label">访问页面</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?php echo number_format($avg_response_time, 3); ?>s</div>
                        <div class="stat-label">平均响应时间</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?php echo $spider_details['last_visit'] ? date('H:i:s', strtotime($spider_details['last_visit'])) : '无'; ?></div>
                        <div class="stat-label">最后访问</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 访问页面列表 -->
        <div class="urls-section">
            <div class="section-header">
                <h3>访问页面列表</h3>
                <p>共 <?php echo count($spider_urls); ?> 个页面被访问</p>
            </div>
            
            <?php if (empty($spider_urls)): ?>
                <div class="empty-state">
                    <div class="empty-state-icon">📄</div>
                    <h3 class="empty-state-title">暂无访问记录</h3>
                    <p class="empty-state-description">该蜘蛛在指定日期没有访问任何页面</p>
                </div>
            <?php else: ?>
                <div class="urls-list">
                    <?php foreach ($spider_urls as $url_data): ?>
                        <div class="url-item">
                            <div class="url-info">
                                <div class="url-path">
                                    <a href="<?php echo esc_url($url_data['url']); ?>" target="_blank">
                                        <?php echo esc_html($url_data['url']); ?>
                                    </a>
                                </div>
                                <div class="url-meta">
                                    <span class="meta-item">
                                        <span class="meta-label">访问时间:</span>
                                        <?php echo date('H:i:s', strtotime($url_data['visit_time'])); ?>
                                    </span>
                                    <span class="meta-item">
                                        <span class="meta-label">响应时间:</span>
                                        <?php echo number_format($url_data['response_time'], 3); ?>s
                                    </span>
                                    <span class="meta-item">
                                        <span class="meta-label">状态码:</span>
                                        <span class="status-code status-<?php echo $url_data['response_code']; ?>">
                                            <?php echo $url_data['response_code']; ?>
                                        </span>
                                    </span>
                                    <?php if ($url_data['page_title']): ?>
                                        <span class="meta-item">
                                            <span class="meta-label">页面标题:</span>
                                            <?php echo esc_html($url_data['page_title']); ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="url-actions">
                                <button class="btn btn-sm btn-secondary" onclick="copyToClipboard('<?php echo esc_js($url_data['url']); ?>')">
                                    📋 复制链接
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <!-- 空状态 -->
        <div class="empty-state">
            <div class="empty-state-icon">🕷️</div>
            <h3 class="empty-state-title">
                <?php if (!$tables_exist): ?>
                    数据库表不存在
                <?php elseif (!$spider_name): ?>
                    请选择蜘蛛
                <?php else: ?>
                    暂无数据
                <?php endif; ?>
            </h3>
            <p class="empty-state-description">
                <?php if (!$tables_exist): ?>
                    请先创建数据库表，然后开始监控蜘蛛访问。
                <?php elseif (!$spider_name): ?>
                    请从上方筛选器中选择一个蜘蛛来查看其访问详情。
                <?php else: ?>
                    该蜘蛛在指定日期没有访问记录。
                <?php endif; ?>
            </p>
        </div>
    <?php endif; ?>
</div>

<script>
jQuery(document).ready(function($) {
    // 筛选器功能
    $('#apply-filter').on('click', function() {
        const spider = $('#spider-select').val();
        const date = $('#date-select').val();
        
        if (!spider) {
            alert('请选择蜘蛛');
            return;
        }
        
        const url = new URL(window.location);
        url.searchParams.set('spider', spider);
        url.searchParams.set('date', date);
        window.location.href = url.toString();
    });

    // 刷新数据
    $('#refresh-details').on('click', function() {
        location.reload();
    });

    // 复制到剪贴板
    window.copyToClipboard = function(text) {
        navigator.clipboard.writeText(text).then(function() {
            // 显示成功提示
            const notification = $('<div class="notification notification-success">链接已复制到剪贴板</div>');
            $('body').append(notification);
            setTimeout(() => notification.fadeOut(), 2000);
        }).catch(function() {
            // 降级方案
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            alert('链接已复制到剪贴板');
        });
    };
});
</script>

<style>
/* 详情页面专用样式 */
.filter-section {
    margin-bottom: 24px;
}

.filter-card {
    background: white;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(59, 130, 246, 0.1);
}

.filter-header h3 {
    margin: 0 0 20px 0;
    color: #1e293b;
    font-size: 18px;
    font-weight: 600;
}

.filter-content {
    display: flex;
    gap: 20px;
    align-items: end;
    flex-wrap: wrap;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.filter-group label {
    font-size: 14px;
    font-weight: 500;
    color: #374151;
}

.filter-select, .filter-input {
    padding: 10px 12px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    font-size: 14px;
    min-width: 200px;
    transition: border-color 0.3s ease;
}

.filter-select:focus, .filter-input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.spider-overview {
    background: white;
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(59, 130, 246, 0.1);
}

.overview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
}

.spider-info {
    display: flex;
    align-items: center;
    gap: 16px;
}

.spider-avatar {
    width: 64px;
    height: 64px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    font-weight: 700;
    color: white;
}

.spider-avatar.google { background: linear-gradient(135deg, #4285f4 0%, #1a73e8 100%); }
.spider-avatar.bing { background: linear-gradient(135deg, #0078d4 0%, #106ebe 100%); }
.spider-avatar.baidu { background: linear-gradient(135deg, #2932e1 0%, #1e1e8f 100%); }
.spider-avatar.other { background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%); }

.spider-details h2 {
    margin: 0 0 4px 0;
    font-size: 24px;
    font-weight: 700;
    color: #1e293b;
}

.spider-details p {
    margin: 0;
    font-size: 14px;
    color: #64748b;
}

.spider-stats-overview {
    display: flex;
    gap: 32px;
    flex-wrap: wrap;
}

.stat-item {
    text-align: center;
}

.stat-value {
    font-size: 28px;
    font-weight: 700;
    color: #1e293b;
    margin: 0;
}

.stat-label {
    font-size: 12px;
    color: #64748b;
    margin: 4px 0 0 0;
}

.urls-section {
    background: white;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(59, 130, 246, 0.1);
}

.section-header {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e2e8f0;
}

.section-header h3 {
    margin: 0 0 4px 0;
    font-size: 20px;
    font-weight: 700;
    color: #1e293b;
}

.section-header p {
    margin: 0;
    font-size: 14px;
    color: #64748b;
}

.urls-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.url-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 20px;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    transition: all 0.3s ease;
}

.url-item:hover {
    border-color: #3b82f6;
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1);
}

.url-info {
    flex: 1;
}

.url-path {
    margin-bottom: 12px;
}

.url-path a {
    color: #3b82f6;
    text-decoration: none;
    font-weight: 500;
    word-break: break-all;
}

.url-path a:hover {
    text-decoration: underline;
}

.url-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    font-size: 13px;
}

.meta-item {
    display: flex;
    align-items: center;
    gap: 4px;
}

.meta-label {
    color: #64748b;
    font-weight: 500;
}

.status-code {
    padding: 2px 8px;
    border-radius: 4px;
    font-weight: 600;
    font-size: 12px;
}

.status-200 { background: #dcfce7; color: #166534; }
.status-301, .status-302 { background: #fef3c7; color: #92400e; }
.status-404 { background: #fee2e2; color: #991b1b; }
.status-500 { background: #fecaca; color: #7f1d1d; }

.url-actions {
    margin-left: 16px;
}

.btn-sm {
    padding: 6px 12px;
    font-size: 12px;
}

.notification {
    position: fixed;
    top: 20px;
    right: 20px;
    background: white;
    border-radius: 8px;
    padding: 12px 16px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border-left: 4px solid #10b981;
    z-index: 10000;
    font-size: 14px;
    color: #059669;
}

@media (max-width: 768px) {
    .filter-content {
        flex-direction: column;
        align-items: stretch;
    }
    
    .filter-select, .filter-input {
        min-width: auto;
    }
    
    .overview-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .spider-stats-overview {
        width: 100%;
        justify-content: space-around;
    }
    
    .url-item {
        flex-direction: column;
        gap: 12px;
    }
    
    .url-actions {
        margin-left: 0;
        align-self: flex-end;
    }
}
</style>
